package com.example.administrator.ksf_zty.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;

import org.json.JSONObject;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;

import static com.example.administrator.ksf_zty.util.AppInfo.getVersionCode;
import static com.example.administrator.ksf_zty.util.HttpUtils.checkUpdate;
import static com.example.administrator.ksf_zty.util.HttpUtils.downloadAdd;
import static com.example.administrator.ksf_zty.util.Tips.show;

/**
 * Created by Mars on 2017-10-21.
 * Common method
 */

public class Common {

    private static long lastClickTime = 0;

    /**
     * 判断是否1秒内多次点击
     * @param ms 判断时间（毫秒）
     */
    public static boolean isFastDoubleClick(int ms) {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < ms) {
            lastClickTime = time;
            return false;
        }
        lastClickTime = time;
        return true;
    }

    /**
     * 选择日期对话框
     * @param context 调用方法的对象
     * @param textView 显示日期的 TextView
     * @param cancel 取消按钮的文字
     * @param separator 日期显示的分隔符
     * @param y 默认年份
     * @param m 默认月份 0-11
     * @param d 默认天数
     */
//    public static void datePicker(Context context, final TextView textView, String cancel,
//                                  final String separator, int y, int m, int d) {
//        DatePickerDialog datePicker = new DatePickerDialog(context,
//                (view, year, monthOfYear, dayOfMonth) -> {
//                    String month = String.valueOf(monthOfYear + 1);
//                    String day = String.valueOf(dayOfMonth);
//                    if (month.length() != 2) {
//                        month = "0" + month;
//                    }
//                    if (day.length() !=2) {
//                        day = "0" + day;
//                    }
//                    String date = String.valueOf(year) + separator + month
//                            + separator + day;
//                    textView.setText(date);
//                }, y, m, d);
//        datePicker.setButton(DialogInterface.BUTTON_NEGATIVE, cancel,
//                (dialog, which) -> {
//                    //将文本内容置为空
//                    textView.setText("");
//                });
//        datePicker.show();
//    }

    /**
     * 线程休眠，不让当前线程霸占该进程所有资源
     * @param ms 休眠时间（毫秒）
     */
    public static void sleep(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开软键盘
     * @param editText 输入框
     * @param context 上下文
     */
    public static void openKeybord(EditText editText, Context context) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(editText, InputMethodManager.RESULT_SHOWN);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                    InputMethodManager.HIDE_IMPLICIT_ONLY);
        }
    }

    /**
     * 关闭软键盘
     * @param editText 输入框
     * @param context 调用方法的对象
     */
    public static void closeKeybord(EditText editText, Context context) {
        InputMethodManager mInputMethodManager =
                (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (mInputMethodManager != null) {
            mInputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
    }

    /**
     * 调用该方法无论手机是否有菜单按键都显示actionbar的菜单按钮
     * @param context 调用方法的对象
     */
    public static void getOverflowMenu(Context context) {

        try {
            ViewConfiguration config = ViewConfiguration.get(context);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String apk = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/KSF.apk";

    /**
     * 检查更新
     */
    public static void checkUpdate(final Activity activity, final Handler handler,
                                   final RelativeLayout relativeLayout, final boolean tip) {
        //在子线程中获取服务器的数据
        Thread thread = new Thread() {
            @Override
            public void run() {
                // 判断是否有访问存储空间权限，只需要判断权限组的其中一个，申请权限会直接获取整个权限组
                if (ContextCompat.checkSelfPermission(activity,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 是否解释申请权限原因
//                        if (ActivityCompat.shouldShowRequestPermissionRationale(SettingActivity.this,
//                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

//                        } else {
                    // 不解释原因，直接申请权限
                    ActivityCompat.requestPermissions(activity,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            123);
                    //                        }
                } else {
                    try {
                        URL url = new URL(checkUpdate);
                        //建立连接
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        //设置请求方式
                        conn.setRequestMethod("GET");
                        //设置请求超时时间
                        conn.setConnectTimeout(5000);
                        //设置读取超时时间
                        conn.setReadTimeout(5000);
                        //判断是否获取成功
                        if (conn.getResponseCode() == 200) {
                            //获得输入流
                            InputStream is = conn.getInputStream();
                            //解析输入流中的数据
                            byte[] buff = new byte[1024];
                            is.read(buff);
                            is.close();
                            String jsons = new String(buff, "UTF-8").trim();
                            JSONObject object = new JSONObject(jsons);

                            if (Integer.parseInt(
                                    getVersionCode(activity)) < Integer.parseInt(object.getString("verCode"))) {
                                Message msg = Message.obtain();
                                msg.obj = downloadAdd + object.getString("apkname");//apk下载地址
                                handler.sendMessage(msg);
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        relativeLayout.setVisibility(View.INVISIBLE);
                                    }
                                });
                            } else {
                                File apkfile = new File(apk);
                                if (apkfile.isFile()) {
                                    //noinspection ResultOfMethodCallIgnored
                                    apkfile.delete();
                                }
                                if (tip) {
                                    activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            show(activity, "已经是最新版本", 1);
                                            relativeLayout.setVisibility(View.INVISIBLE);
                                        }
                                    });
                                }
                            }
                        } else {
                            if (tip) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        show(activity, "服务器异常，检查更新失败", 1);
                                        relativeLayout.setVisibility(View.INVISIBLE);
                                    }
                                });
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        //启动线程
        thread.start();
    }
}
